#!/usr/bin/python3
# -*- coding: utf-8 -*-

import os
import sys
import icu
from mutagen.easyid3 import EasyID3
from mutagen.mp3 import MP3


def parse(argv):
    command = ''
    option = 'auto'
    filepath = None
    destpath = None
    files = []
    idx = 1
    cnt = len(argv)

    while idx < cnt:
        if argv[idx] in ("h", "-h", "-?", "--help"):
            command = 'help'
            break
        elif argv[idx] in ("l", "-l"):
            command = 'list'
        elif argv[idx] in ("t", "-t"):
            command = 'test'
        elif argv[idx] in ("a", "-a"):
            command = 'create'
        elif argv[idx] in ("x", "-x"):
            command = 'extract'
        elif argv[idx] in ("xn", "-xn"):
            command = 'extract_no_folder'
        elif argv[idx] in ("xf", "-xf"):
            command = 'extract_filename_folder'
        elif argv[idx] in ("xi", "-xi"):
            command = 'extract_intelligent_folder'
        elif argv[idx] in ("-o", "-enc"):
            idx += 1
            option = argv[idx]
        else:
            fp = os.path.abspath(argv[idx])
            if command.startswith('extract') or command == 'list' or command == 'test':
                if os.path.isfile(fp):
                    files.append(fp)
                else:
                    destpath = fp
            elif command == 'create':
                if os.path.exists(fp):
                    files.append(fp)
                else:
                    filepath = fp
            elif os.path.exists(fp):
                files.append(fp)
            else:
                command = 'help'
                # print('parse error : ' + argv[idx])
        idx += 1

    if command is not None: print('command : ' + command)
    if option is not None: print('option : ' + option)
    if filepath is not None: print('filepath : ' + filepath)
    if destpath is not None: print('destpath : ' + destpath)
    if len(files) > 0: print('files : ' + str(len(files)))
    return command, option, filepath, destpath, files


def get_encoding(text, encoding='auto'):
    enc = encoding
    dec = 'cp437'
    # noinspection PyBroadException
    try:
        text = text.encode(dec)
    except:
        dec = 'utf-8'
        text = text.encode(dec)

    if encoding == 'auto':
        enc = icu.CharsetDetector(text).detect().getName()
        # self.ENCODING = chardet.detect(names)['encoding']

    return enc, dec

if __name__ == "__main__":
    print('myarc 0.0.1')
    path = os.getcwd()
    argc = len(sys.argv)
    cmd, opt, file, path, files = parse(sys.argv)
    print(EasyID3.valid_keys.keys())
    for f in files:
        #from mutagen.easyid3 import EasyID3
        #from mutagen.mp3 import MP3
        #audio = MP3(f, ID3=EasyID3)
        #audio = MP3(f)
        audio = EasyID3(f)
        print('')
        print(os.path.basename(f))
        ss = audio.pprint()
        ENCODING, DECODING = get_encoding(ss, 'auto')
        print(ENCODING, DECODING)
        print(ss)
        '''
        print(os.path.basename(f))
        try: artist = str(audio["TPE1"])
        except KeyError: artist = ''
        try: album = str(audio["TALB"])
        except KeyError: album = ''
        try: title = str(audio["TIT2"])
        except KeyError:
            try: title = str(audio["TIT1"])
            except KeyError: title = ''
        sss = artist + album + title
        ENCODING, DECODING = get_encoding(sss, 'auto')
        print(ENCODING, DECODING)
        print(artist) #.encode(DECODING).decode(ENCODING))
        print(album) #.encode(DECODING).decode(ENCODING))
        print(title) #.encode(DECODING).decode(ENCODING))
        '''
        '''
        # print('album', audio['album'])
        # print('artist', audio['artist'])
        # print('title', audio['title'])
        # for s in audio['title']:
        #     print(s)
        '''

